<?php

require_once 'FWidget.class.php';

class FToolbarMenu extends FWidget
{
    
    private $handler;
    
    public function __construct($name, $text = '')
    {
        parent::__construct($name);
        $this->setText($text);
    }
    
    public function generate()
    {
        $jsCode .= " { ";
        
        if ( strlen($this->getText()) )
        {
            $jsCode .= " text: '{$this->getText()}', ";
        }
        
        if ( strlen($this->getCls()) )
        {
            $jsCode .= " cls: '{$this->getCls()}', ";
        }
        
        if ( $this->getHeight() )
        {
            if ( is_int($this->getHeight()) )
            {
                $jsCode .= " height: {$this->getHeight()}, ";
            }
            else
            {
                $jsCode .= " height: '{$this->getHeight()}', ";
            }
        }
        
        if ( $this->getWidth() )
        {
            if ( is_int($this->getWidth()) )
            {
                $jsCode .= " width: {$this->getWidth()}, ";
            }
            else
            {
                $jsCode .= " width: '{$this->getWidth()}', ";
            }
        }
        
        // Items
        if ( count($this->getItems()) > 0 )
        {
            $jsCode .= ' menu: [ ';
            // array_reverse para o menu seguir a ordem de como os itens foram adicionados.
            foreach ( array_reverse($this->getItems()) as $item )
            {
                if ( $item instanceof FToolbarMenu )
                {
                    $jsCode .= $item->generate() . ',';
                }
            }
            $jsCode .= ' ],';
        }
        
        // Handler
        if ( $this->getHandler() )
        {
            if ( $this->getHandler() instanceof FForm )
            {
                $this->getHandler()->generate();
                $jsCode .= ' handler: function() { ' . $this->getHandler()->show() . '},';
            }
            elseif ( $this->getHandler() instanceof FMessage )
            {
                
            }
            else
            {
                $jsCode .= ' handler: function() { ' . $this->getHandler() . '},';
            }
        }
            
        $jsCode .= " } ";

        return $jsCode;
    }
    
    public function getHandler() {
        return $this->handler;
    }

    public function setHandler($handler)
    {
        $this->handler = $handler;
    }
    
    public function addItem($item)
    {
        if ( $item instanceof FToolbarMenu )
        {
            parent::addItem($item);
        }
    }
    
}

?>
